<!-- pages/partner/chat.vue -->
<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-info">
        <text class="chat-username">{{partnerInfo.name}}</text>
        <text class="chat-status" v-if="partnerInfo.online">在线</text>
        <text class="chat-status offline" v-else>离线</text>
      </view>
      <view class="nav-actions">
        <text class="action-icon">⋮</text>
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view 
      scroll-y 
      class="chat-messages" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
    >
      <view class="load-more" v-if="hasMoreMessages">
        <text>加载更多消息...</text>
      </view>
      
      <view 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message-wrapper', message.isSelf ? 'self' : 'partner']"
      >
        <view class="message-time" v-if="showMessageTime(index)">
          <text>{{message.time}}</text>
        </view>
        
        <view class="message-item">
          <view class="avatar" v-if="!message.isSelf">
            <text class="avatar-emoji">{{partnerInfo.avatar}}</text>
          </view>
          
          <view class="message-content">
            <view class="message-bubble">
              <text>{{message.content}}</text>
            </view>
            <view class="message-status" v-if="message.isSelf">
              <text v-if="message.status === 'sending'">发送中...</text>
              <text v-else-if="message.status === 'sent'">已发送</text>
              <text v-else-if="message.status === 'read'">已读</text>
              <text v-else-if="message.status === 'failed'" class="status-failed">发送失败</text>
            </view>
          </view>
          
          <view class="avatar" v-if="message.isSelf">
            <text class="avatar-emoji">😊</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="chat-input-area">
      <view class="input-toolbar">
        <text class="toolbar-icon">😊</text>
        <text class="toolbar-icon">🖼️</text>
        <text class="toolbar-icon">📝</text>
      </view>
      
      <view class="input-box">
        <textarea 
          class="message-input"
          v-model="newMessage"
          placeholder="发送消息..."
          :cursor-spacing="20"
          :maxlength="-1"
          :show-confirm-bar="false"
          :auto-height="true"
          @focus="onInputFocus"
        />
        <view class="send-btn" @tap="sendMessage" :class="{ 'active': newMessage.trim() }">
          <text>发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'

// 模拟获取路由参数
const partnerId = 5 // 实际应从路由获取: uni.getQueryString('id')

// 聊天相关状态
const newMessage = ref('')
const scrollTop = ref(0)
const hasMoreMessages = ref(true)

// 模拟搭子信息
const partnerInfo = ref({
  id: partnerId,
  name: '刘七',
  avatar: '👩‍🎓',
  major: '数学',
  targetSchool: '中国科学技术大学',
  online: true
})

// 模拟聊天记录
const messages = ref([
  {
    id: 1,
    content: '嗨，准备考研还顺利吗？',
    time: '昨天 20:15',
    isSelf: false,
    status: 'read'
  },
  {
    id: 2,
    content: '还可以，最近在刷线代题，有点吃力。你呢？',
    time: '昨天 20:18',
    isSelf: true,
    status: 'read'
  },
  {
    id: 3,
    content: '我在准备政治，感觉内容太多了，有什么好的记忆方法吗？',
    time: '昨天 20:20',
    isSelf: false,
    status: 'read'
  },
  {
    id: 4,
    content: '政治的话，我觉得做思维导图挺有用的，可以把知识点串起来。',
    time: '昨天 20:25',
    isSelf: true,
    status: 'read'
  },
  {
    id: 5,
    content: '对了，我整理了一些线代的笔记，要不要我分享给你？',
    time: '今天 10:15',
    isSelf: true,
    status: 'read'
  },
  {
    id: 6,
    content: '太好了！非常感谢！我正需要这个。',
    time: '今天 10:20',
    isSelf: false,
    status: 'read'
  }
])

// 判断是否显示消息时间
const showMessageTime = (index) => {
  if (index === 0) return true
  
  const currentMsg = messages.value[index]
  const prevMsg = messages.value[index - 1]
  
  // 如果当前消息和上一条消息时间相差超过5分钟，则显示时间
  // 这里简化处理，直接根据时间字符串判断
  return currentMsg.time !== prevMsg.time
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim()) return
  
  // 添加新消息
  const newMsg = {
    id: Date.now(),
    content: newMessage.value,
    time: '刚刚',
    isSelf: true,
    status: 'sending'
  }
  
  messages.value.push(newMsg)
  newMessage.value = ''
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
  
  // 模拟发送过程
  setTimeout(() => {
    const msgIndex = messages.value.findIndex(m => m.id === newMsg.id)
    if (msgIndex !== -1) {
      messages.value[msgIndex].status = 'sent'
    }
    
    // 模拟对方已读
    setTimeout(() => {
      const msgIndex = messages.value.findIndex(m => m.id === newMsg.id)
      if (msgIndex !== -1) {
        messages.value[msgIndex].status = 'read'
      }
      
      // 模拟对方回复
      setTimeout(() => {
        const replyMsg = {
          id: Date.now(),
          content: '好的，我会查看一下！等我学习完再交流。',
          time: '刚刚',
          isSelf: false,
          status: 'read'
        }
        
        messages.value.push(replyMsg)
        nextTick(() => {
          scrollToBottom()
        })
      }, 3000)
    }, 1000)
  }, 1000)
}

// 滚动到底部
const scrollToBottom = () => {
  // 由于scroll-view的设计，需要设置一个足够大的值来确保滚动到底部
  scrollTop.value = 99999
}

// 加载更多消息
const loadMoreMessages = () => {
  // 模拟加载更多历史消息
  uni.showLoading({
    title: '加载中...'
  })
  
  setTimeout(() => {
    // 模拟加载3条历史消息
    const historyMessages = [
      {
        id: -1,
        content: '我们一起加油！',
        time: '三天前',
        isSelf: true,
        status: 'read'
      },
      {
        id: -2,
        content: '嗯嗯，互相督促！',
        time: '三天前',
        isSelf: false,
        status: 'read'
      },
      {
        id: -3,
        content: '你是准备考哪个学校的研究生？',
        time: '三天前',
        isSelf: true,
        status: 'read'
      }
    ]
    
    messages.value = [...historyMessages, ...messages.value]
    
    // 假设已经没有更多消息了
    hasMoreMessages.value = false
    
    uni.hideLoading()
  }, 1000)
}

// 输入框获取焦点时滚动到底部
const onInputFocus = () => {
  nextTick(() => {
    scrollToBottom()
  })
}

// 返回上一页
const navigateBack = () => {
  uni.navigateBack()
}

// 页面加载完成后滚动到底部
onMounted(() => {
  nextTick(() => {
    scrollToBottom()
  })
})
</script>

<style>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f1f1f1;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background: linear-gradient(135deg, #A8BF8F 0%, #8FA876 100%);
  padding: 0 20rpx;
}

.nav-back {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.nav-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.chat-username {
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
}

.chat-status {
  font-size: 22rpx;
  color: #e8f5e9;
  margin-top: 2rpx;
}

.chat-status.offline {
  color: #f5f5f5;
}

.nav-actions {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon {
  color: #fff;
  font-size: 40rpx;
  font-weight: bold;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
}

.load-more {
  text-align: center;
  padding: 20rpx 0;
}

.load-more text {
  font-size: 24rpx;
  color: #999;
}

.message-wrapper {
  margin-bottom: 20rpx;
}

.message-time {
  text-align: center;
  margin: 20rpx 0;
}

.message-time text {
  background: rgba(0, 0, 0, 0.1);
  color: #666;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin-top: 16rpx;
}

.message-wrapper.self .message-item {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 16rpx;
}

.avatar-emoji {
  font-size: 40rpx;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 16rpx 24rpx;
  border-radius: 12rpx;
  position: relative;
  word-break: break-all;
}

.message-wrapper.partner .message-bubble {
  background-color: #ffffff;
  border: 1px solid #eee;
}

.message-wrapper.self .message-bubble {
  background-color: #daf0d1;
  color: #333;
}

.message-status {
  font-size: 22rpx;
  color: #999;
  text-align: right;
  margin-top: 4rpx;
}

.status-failed {
  color: #ff4d4f;
}

.chat-input-area {
  background-color: #fff;
  border-top: 1rpx solid #eee;
  padding: 10rpx 20rpx;
  padding-bottom: calc(10rpx + env(safe-area-inset-bottom));
}

.input-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.toolbar-icon {
  font-size: 36rpx;
  padding: 10rpx 20rpx;
  color: #666;
}

.input-box {
  display: flex;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  min-height: 68rpx;
  max-height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.send-btn {
  background-color: #e0e0e0;
  color: #999;
  border-radius: 8rpx;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  height: 68rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn.active {
  background-color: #8FA876;
  color: #fff;
}
</style>